/*
 * @Author: your name
 * @Date: 2021-05-30 11:23:26
 * @LastEditTime: 2022-01-16 20:21:10
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \telescope720P\src\page_handle.cpp
 */
#include "page_handle.h"
#include "xlog.h"
PageHandle::PageHandle()
{
    page.reset(nullptr);
}
PageHandle::~PageHandle()
{
}
bool PageHandle::PageOpen(std::string windowName)
{
    Widget *pagePtr = GuiEngine::GetInstance().WindowOpen(windowName.c_str());
    if (pagePtr && pagePtr->IsValid())
    {
        SetPage(pagePtr);
        return true;
    }
    else
    {
        if (pagePtr)
        {
            delete pagePtr;
        }
        return false;
    }
}
bool PageHandle::PageClose()
{
    Release();
    return GuiEngine::GetInstance().WindowClose(page.get());
}
void PageHandle::SetKeyEvent(KeyCmdMapTable event)
{
    keyEvent = event;
}
void PageHandle::SaveContext(Context *ctx)
{
    std::lock_guard<std::mutex> locker(m_mutex);
    ctxQueue.push_back(ctx);
}
Widget *PageHandle::GetThisPage()
{
    return page.get();
}
KeyCmdMapTable &PageHandle::GetKeyEvent()
{
    return keyEvent;
}
void PageHandle::KeyEventRedefine(KeyboardValue key, KeyCmd cmd)
{
    keyEvent.table[static_cast<int>(key)] = cmd;
}
void PageHandle::Release()
{
    Context *ctx = nullptr;
    std::lock_guard<std::mutex> locker(m_mutex);
    while (!ctxQueue.empty())
    {
        ctx = ctxQueue.front();
        if (ctx)
        {
            delete ctx;
            ctx = nullptr;
        }
        ctxQueue.pop_front();
    }
}
void PageHandle::SetPage(Widget *p)
{
    page.reset(p);
}
std::unique_ptr<Widget> &PageHandle::GetUniquePtrPage()
{
    return page;
}